<template>
	<view class="container">
		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading">
			<text>正在定位，请稍候...</text>
		</view>

		<!-- 地图容器 -->
		<map
			v-else
			id="map"
			class="map"
			:latitude="location.latitude"
			:longitude="location.longitude"
			@tap="moveLocation"
			:scale="scale"
			:markers="markers"
			:polygons="polygons"
			:circles="circles"
			show-location
		></map>

		<!-- 控制面板 -->
		<view class="control-panel">
			<!-- 距离滑块 -->
			<view class="title">
				<text>邻里服务管家申请</text>
			</view>
			<view class="distance-control">
				<text class="distance-label">服务半径：{{ receiveDistance }}米，(注：如需超过2公里请与客服联系)）</text>
				<slider
					:value="receiveDistance"
					:min="500"
					:max="2000"
					:step="200"
					@change="changeDistance"
					activeColor="#4a90e2"
					backgroundColor="#e5e5e5"
					block-color="#4a90e2"
					block-size="20"
					class="slider"
				/>
			</view>

			<!-- 操作按钮 -->
			<view class="button-group">
				<button class="map-btn" @tap="moveToMyLocation">我的位置</button>
				<button class="map-btn" @click="reg">提交申请</button>
			</view>
		</view>
	</view>
</template>

<script>
const DEFAULT_LAT = 26.042786;
const DEFAULT_LNG = 119.216902;
const db = uniCloud.databaseForJQL();
import { eventBus } from '../../utils/eventBus';
export default {
	data() {
		return {
			receiveDistance:500,
			user: {},
			own: {
				name: '',
				photo: '',
				signature: '', //本人服务宗旨
				sex: '',
				age: '',
				address: '',
				telphone: ''
			},
			radio: 500,
			scale: 16,
			isLoading: true,
			Location: {
				latitude: DEFAULT_LAT,
				longitude: DEFAULT_LNG
			},
			circles: [
				{
					latitude: 26.042786,
					longitude: 119.216902,
					color: '#000000AA',
					fillColor: '#0000002a',
					radius: 500,
					strokeWidth: 5
				}
			],
			markers: [],
			polygons: [
				// {
				// 	points: [
				// 		{ latitude: 26.042666, longitude: 119.216702 },
				// 		{ latitude: 26.042886, longitude: 119.216902 },
				// 		{ latitude: 26.042823, longitude: 119.216662 }
				// 	],
				// 	strokeWidth: 5,
				// 	strokeColor: '#CC6633',
				// 	fillColor: '#CC66256F'
				// }
			],
			mapReady: false,
			mapContext: null
		};
	},

	async mounted() {
		await this.initializeLocation();
		this.handleMapReady();
	},

	methods: {
		// 假设这是在一个全局作用域或者类方法中定义的函数
		reg() {
			
			console.log('.....')
			uni.navigateTo({
			url:'/pages/regOwn/regOwn'
			})
			// 创建 groupInfo 对象
		// 	const groupInfo = {
		// 		groupId: Date.now(), // 正确获取当前时间戳
		// 		groupName: '',
		// 		location: new db.Geo.Point(this.Location.longitude, this.Location.latitude), // 修正地理坐标点创建方式
		// 		radio: this.radio,
		// 		groupOwn: this.own,
		// 		groupPicPath: '', // 群标志图
		// 		signature: '', // 群个性口号
		// 		registTime: Date.now() // 正确获取当前时间戳
		// 	};

		// 	// 向数据库中添加文档
		// 	db.collection('Group')
		// 		.add(groupInfo)
		// 		.then((res) => {
		// 			console.log('群信息添加成功', res);
		// 		})
		// 		.catch((err) => {
		// 			console.error('群信息添加失败', err);
		// 		});
		 },

		// 初始化定位
		async initializeLocation() {
			try {
				const { latitude, longitude } = await uni.getLocation({
					type: 'gcj02',
					altitude: true
				});

				this.location = {
					latitude: latitude || DEFAULT_LAT,
					longitude: longitude || DEFAULT_LNG
				};
				this.inintCircle(this.location, this.receiveDistance);
				console.log('定位成功:', this.location);

				// 添加当前定位标记
			} catch (error) {
				console.error('定位失败:', error);
				uni.showToast({
					title: '定位失败，使用默认位置',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		//初始化自己位置范围
		inintCircle(location, radius) {
			const circles = {
				latitude: location.latitude,
				longitude: location.longitude,
				color: '#000000AA',
				fillColor: '#0000002a',
				radius: radius,
				strokeWidth: 5
			};
			this.circles[0] = circles;
		},

		// 地图准备就绪
		handleMapReady() {
			this.mapContext = uni.createMapContext('map', this);
			this.mapReady = true;
			this.adjustMapView();
		},

		// 调整地图视野
		adjustMapView() {
			if (!this.mapReady) return;

			this.mapContext.moveToLocation({
				latitude: this.location.latitude,
				longitude: this.location.longitude
			});

			this.mapContext.includePoints({
				points: this.markers.map((m) => ({
					latitude: m.latitude,
					longitude: m.longitude,
					
				})),
				padding: [50, 50, 50, 50]
			});
		},

		// 缩放控制
		scaleChange(type) {
			this.scale = Math.min(20, Math.max(3, type === '+' ? this.scale + 1 : this.scale - 1));
		},

		// 距离调节
		changeDistance(e) {
			this.radio = e.detail.value;
			this.circles[0].radius = e.detail.value;
			uni.$emit('ditance', e.detail.value);
			this.adjustMapView();
		},

		// 添加标记
		addMarker() {
			const newMarker = {
				id: Date.now(),
				latitude: this.location.latitude + (Math.random() - 0.5) * 0.001,
				longitude: this.location.longitude + (Math.random() - 0.5) * 0.001,
				iconPath: '/static/nicPic/w2.png',
				width: 12,
				height: 12
			};
			this.markers = [...this.markers, newMarker];
			this.$nextTick(this.adjustMapView);
		},

		moveLocation(e) {
			// 保存 Vue 实例的 this 到变量 vm
			const vm = this;
			this.mapContext.getCenterLocation({
				success(res) {
					// 更新 location 对象
					vm.Location = {
						longitude: res.longitude,
						latitude: res.latitude
					};
				   
					// 更新 circles 数组中的第一个元素
					vm.circles = [
						{
							...vm.circles[0],
							longitude: res.longitude,
							latitude: res.latitude
						}
					];
					const newLocation = {
						id: vm.user.userId,
						latitude: vm.location.latitude,
						longitude: vm.location.longitude,
						iconPath: vm.user.nicPic,
						width: 1,
						height: 1
					};
					vm.markers = vm.replaceElementById(vm.markers, newLocation);
				}
			});
		},

		replaceElementById(arr, newElement) {
			const index = arr.findIndex((item) => item.id === newElement.id);
			if (index !== -1) {
				arr.splice(index, 1, newElement);
			} else {
				arr.push(newElement);
			}
			return arr;
		},

		// 返回当前位置
		async moveToMyLocation() {
			var that = this;
			if (!this.mapReady) return;
			const res = await uni.getLocation({
				type: 'gcj02',
				altitude: true
			});
			this.location.longitude = res[1].longitude;
			this.location.latitude = res[1].latitude;
			console.log('坐标' + JSON.stringify(res));
			this.mapContext.moveToLocation({
				latitude: that.location.latitude,
				longitude: that.location.longitude
			});
			this.inintCircle(this.location, this.receiveDistance);
		}
	}
};
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
}
.title {
	width: 100%;
	align-items: center;
}
.loading {
	padding: 30rpx;
	text-align: center;
	color: #666;
}

.map {
	flex: 1;
	width: 100%;
}

.control-panel {
	padding: 20rpx;
	background: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.distance-control {
	padding: 20rpx;
	background: #f8f8f8;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
}

.distance-label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 15rpx;
}

.slider {
	margin: 0 20rpx;
}

.button-group {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 15rpx;
}

.map-btn {
	font-size: 26rpx;
	padding: 12rpx;
	background: #4a90e2;
	color: white;
	border-radius: 8rpx;
	line-height: 1.5;
}

.map-btn:active {
	opacity: 0.8;
}
</style>
